package com.dts.evaluate.service;

import android.app.Application;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;

import com.dts.evaluate.R;
import com.dts.evaluate.common.Constants;
import com.dts.evaluate.common.SocketType;
import com.dts.evaluate.controller.impl.DataImpl;
import com.dts.evaluate.controller.intf.DataInterface;
import com.dts.evaluate.utils.LogUtil;
import com.dts.evaluate.utils.StringUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Request;
import okhttp3.Response;

public class CameraMediaRecordService extends Service implements SurfaceHolder.Callback{

    private MediaRecorder mediaRecorder;
    private SurfaceView surfaceView;
    private View floatView;
    private SurfaceHolder surfaceHolder;
    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;
    private boolean isRecording = false;
    private Camera camera;
    private  Timer timer;

    private File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);

    public CameraMediaRecordService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();


    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //为了让surfaceview显示完成，这里休眠500毫秒后再开始录制
        String flag = intent.getStringExtra(Constants.VIDEO_TYPE);
        final String videoId = intent.getStringExtra(Constants.VIDEO_ID);
        if(SocketType.CALL_BACK_START_VIDEO.equals(flag)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    startRecord(videoId);
                }
            }).start();
        }else {
            stopRecord();
        }
        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * 提交视频路径到服务器
     * @param path
     */
    private void commitPathToServer(String id,String name,String path){
        DataInterface dataInterface = new DataImpl();
        dataInterface.commitVideoPath(Constants.VIDEO_URL, id, name, path, new StringCallback() {
            @Override
            public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

            }
        }, this);
    }


    /**
     * 初始化surfaceview
     */
    private void init(){
        layoutParams = new WindowManager.LayoutParams();
        windowManager = (WindowManager) getApplication().getSystemService(Application.WINDOW_SERVICE);

        //设置window type
        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        //设置图片格式，效果背景透明
        layoutParams.format = PixelFormat.RGB_888;
        //设置悬浮窗口不能聚焦
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
        //设置悬浮窗口在左上
        layoutParams.gravity = Gravity.LEFT|Gravity.TOP;

        layoutParams.x = 0;
        layoutParams.y = 0;

        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

        floatView = LayoutInflater.from(getApplication()).inflate(R.layout.camera_surface_layout,null);
        windowManager.addView(floatView,layoutParams);

        surfaceView = (SurfaceView) floatView.findViewById(R.id.surface_view);

        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        // setType必须设置，要不出错.
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    /**
     * 停止录像
     */
    public void stopRecord() {
        if(isRecording && mediaRecorder!=null){
            mediaRecorder.stop();
        }
        release();
        isRecording = false;
        //移除摄像界面
        windowManager.removeView(floatView);
        //停止该录像服务
        stopSelf();
    }

    /**
     * 获取Camera
     * @return
     */
    public Camera getCameraInstance() {
        Camera c = null;
        int num = Camera.getNumberOfCameras();
        for (int i = 0; i < num; i++) {
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                c = Camera.open(i);
                return c;
            }
        }
        return Camera.open();
    }


    /**
     * 开始录像
     */
    public void startRecord(String videoId) {
        if(StringUtils.isEmpty(videoId)){
            return;
        }
        if(isRecording){
            return;
        }
      /*  if(isRecording){
            if(timer != null){
                timer.cancel();
            }
            stopRecord();
        }*/
        this.camera = getCameraInstance();
        //也许会请求权限，如果被拒绝，camera会为null
        if(this.camera == null){
            return;
        }
        camera.unlock();
        mediaRecorder = new MediaRecorder();// 创建mediarecorder对象
        // 设置录制视频源为Camera(相机)
        mediaRecorder.reset();
        mediaRecorder.setCamera(this.camera);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
        mediaRecorder
                .setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        // 设置录制的视频编码h263 h264
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        // 设置视频录制的分辨率。必须放在设置编码和格式的后面，否则报错
        mediaRecorder.setVideoSize(176, 144);
        // 设置录制的视频帧率。必须放在设置编码和格式的后面，否则报错
        mediaRecorder.setVideoFrameRate(20);
        mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        // 设置视频文件输出的路径

       /* File file = new File(dir,name);*/
        File dir  = new File("/sdcard/evaluate");
        if(!dir.exists()){
            dir.mkdir();
        }
        LogUtil.v("videoId:"+videoId);
        String name = videoId+".3gp";
        mediaRecorder.setOutputFile("/sdcard/evaluate/"+name);


        try {
            // 准备录制
            LogUtil.v("prepare1");
            mediaRecorder.prepare();
            LogUtil.v("preparee");
            // 开始录制
            mediaRecorder.start();
            LogUtil.v("start");
            isRecording = true;

            //提交视屏数据到服务器
            commitPathToServer(videoId,name,"/sdcard/evaluate/"+videoId+".3gp");

            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if(isRecording){
                        stopRecord();
                    }
                }
            },5*60*1000);
            Log.v("tag","正在录像------------------>");
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            Log.v("tag","录像异常----------------------->");
            release();
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.v("tag","录像异常----------------------->");
            release();
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(timer != null){
            timer.cancel();
        }
    }

    /**
     * 释放camera和mediaRecorder
     */
    public void release(){
        if(mediaRecorder != null){
            mediaRecorder.setOnErrorListener(null);
            mediaRecorder.setPreviewDisplay(null);
            mediaRecorder.release();
            mediaRecorder = null;
        }
        if(camera != null){
            camera.stopPreview();
            camera.lock();
            camera.release();
            camera = null;
        }
        isRecording = false;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        this.surfaceHolder = holder;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        this.surfaceHolder = holder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        this.mediaRecorder = null;
        this.surfaceHolder = null;
        this.surfaceView = null;
    }

}
